package com.rrx.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rrx.model.Users;
import com.rrx.service.UsersService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;


@Controller
public class UsersController {

    @Resource
    UsersService usersService;
    // 小程序的唯一标示ID
    private static final String wxspAppid = "wx1482a5aea3785f9a";
    // 小程序的 app secret (在微信小程序管理后台获取)
    private static final String wxspSecret = "370cd68a3e99be23e587b43993eca3c1";
    // 授权（必填）
    private static final String grant_type = "authorization_code";


    /**
     * 通过获取的code得到用户的openID
     * @param code 前端通过wx.login获取code
     * @return 返回openID
     */
    @RequestMapping("/wxdecodeUserInfo")
    @ResponseBody
    public String decodeUserInfo(String code){
        //请求参数
        String parmas = "appid=" + wxspAppid + "&secret=" + wxspSecret + "&js_code=" + code + "&grant_type=" + grant_type;
        try {
            URL url = new URL("https://api.weixin.qq.com/sns/jscode2session?"+parmas);//接口地址
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.connect();//建立链接
            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line;
            StringBuilder sb = new StringBuilder();
            while((line = br.readLine()) != null) {
                sb.append(line);
            }
            br.close();
            connection.disconnect();
            String json = sb.toString();
            String oid = json.substring(json.indexOf("openid\":\"")+9, json.lastIndexOf("\""));
//            System.out.println(oid);

            //查询数据库是否存在openID相同的用户

            String openid= usersService.getOpenid(oid);
            System.out.println(openid);

            //数据库没有存在相同的用户就把获取到的用户信息存到数据库
            if (openid==null){
                Timestamp time = new Timestamp(new Date().getTime());
                usersService.insertUsers( oid, time);
                return "true";
            }else{
//                Integer state=usersService.selectState(openid);//通过openID查询用户状态  0为可用  1为被冻结

//                Integer userid=usersService.selectUserid(openid);
//                String phone=usersService.selectPhone(openid);
                Users user = usersService.getUserInfo(openid);
//                Integer state = usersService.selectState(openid);
//                if ( state != 0 ){
//                    return "false";
//                }
                if (user != null){
                    ObjectMapper mapper = new ObjectMapper();
                    json = mapper.writeValueAsString(user);
                    System.out.println(json);
                    return json;
                }else {
                    return "false";
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "false";
    }
}